package com.yz.renter.utils;

import com.yz.renter.login.pojos.User;
import com.yz.renter.login.service.impl.UserServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class RRealm extends AuthorizingRealm {
    @Autowired
    private UserServiceImpl userService;

    /**
     * 授权
     *
     * @param principalCollection
     * @return
     */
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //1.获取授权用户信息（principalCollection存放了认证成功的用户信息）
        //String username = (String)principalCollection.iterator().next();
//        Memeber memeber = (Memeber) principalCollection.iterator().next();
//        String memeberId = memeber.getMemeberId();

//        //2.通过user的id查询当前用户的所有角色名 ---- Set<String>
//        Set<String> roles = roleDAO.queryRolesByUserId(userId);
//
//        //3.通过user的id查询当前用户的所有权限percode ---- Set<String>
//        Set<String> permissions = permissionDAO.queryPermissionsByUserId(userId);

//        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
//        authorizationInfo.setRoles(roles);
//        authorizationInfo.setStringPermissions(permissions);
//        return authorizationInfo;
        //1、获取当前登录的用户信息
        User user = (User) SecurityUtils.getSubject().getPrincipal();

        return null;
    }

    /**
     * 认证
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //1.从token中获取用户名
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String phone = token.getUsername();
        String password = new String(token.getPassword());

        //2.根据用户名查询数据库（UserDAO）,得到一个User对象

        User user = userService.findUser(token.getUsername());
        if (user == null) {
            throw new UnknownAccountException("帐号不存在！");
        } else {
            //用户存在则验证密码
            String md5Pwd = new SimpleHash("MD5",password).toHex();
            System.out.println(md5Pwd);
//            if (!md5Pwd.equals(member.getPassword())){
            if (!user.getPassword().equals(md5Pwd)){
                throw new IncorrectCredentialsException("密码错误！");
            }
        }
        //                                   Object   String   String
        return new SimpleAuthenticationInfo(user,password,getName());

    }


    @Override
    public String getName() {
        return "myRealm01";
    }
}
